<?php
/**
 * Created by PhpStorm.
 * User: LFL
 * Date: 2010/5/25
 * Time: 16:02
 */
namespace api\controllers;

use Faker\Provider\Uuid;
use Yii;
use common\helps\tools;
use yii\web\Controller;
use backend\models\Materiel;

class BillController extends Controller
{


    /**
     * 获取当天的前一笔生效订单的金额
     */
    private function getTodayPreBillPrices($shopId)
    {
        $curDate = date('Y-m-d'); //当前日期
        $sql = "SELECT preBillNo,shopId,totalMaterielPrice,deliveryFee1,deliveryFee2,payPrice FROM j_bill_pre WHERE ShopID = " . $shopId . " AND billStatus = 2 AND createTime >= '" . $curDate . " 00:00:00' AND createTime <= '" . $curDate . " 23:59:59'";
        $pre_bill = Yii::$app->db->createCommand($sql)->queryOne();
        if ($pre_bill) {
            $pre_bill_dtl_sql = "SELECT m.storeType, SUM( dtl.salePrice*dtl.qty) AS price FROM j_bill_dtl_pre dtl JOIN j_materiel m ON m.id = dtl.materielId WHERE dtl.preBillNo = '" . $pre_bill['preBillNo'] . "' GROUP BY m.storeType";
            $pre_bill_dtls = Yii::$app->db->createCommand($pre_bill_dtl_sql)->queryAll();
            $pre_bill_dtl_price = [];
            foreach ($pre_bill_dtls as $price) {
                $pre_bill_dtl_price[$price['storeType']] = $price['price'];
            }
            $pre_bill['prices'] = $pre_bill_dtl_price;
            return $pre_bill;
        }
        return null;
    }

    /**
     * 获取门店限额(按属性)
     * @param $shopId
     * @return array
     */
    public function getShopLimit($shopId)
    {

        $tmpStoreLimit = [];
        $ck_limit_sql = "SELECT sc.config_key,sc.config_value,sl.lower_limit from j_sys_config sc 
                                left join j_shop_limit sl on sc.config_key = sl.storeType and sl.shopId = " . $shopId . "
                                where sc.config_group_id = 'storeType'";
        $shopStoreLimit = Yii::$app->db->createCommand($ck_limit_sql)->queryAll();
        foreach ($shopStoreLimit as $limit) {
            $tmpStoreLimit[$limit['config_key']] = $limit['lower_limit'];
        }
        return $tmpStoreLimit;
    }


    private function calcDeliveryFee($shop, $materielArray)
    {
        $rate = 0.1; //费率
        //运费
        $deliveryFees = [
            'limit_model' => $shop['limit_mode'],
            'deliveryFee1' => 0,
            'deliveryFee2' => 0
        ];
        $pre_bill = $this->getTodayPreBillPrices($shop['ShopID']);

        $totalPrice = 0; //总金额
        $materielPrices = []; //小计金额（根据属性统计）
        foreach ($materielArray as $ma) {
            $totalPrice += ($ma['qty'] * $ma['salePrice']);
            $subPrice = $ma['qty'] * $ma['salePrice'];
            if (isset($materielPrices[$ma['storeType']])) {
                $materielPrices[$ma['storeType']] += $subPrice;
            } else {
                $materielPrices[$ma['storeType']] = $subPrice;
            }
        }

        if ($shop['limit_mode'] == 1) {

            //按总额计算运费
            if ($totalPrice < $shop['lower_limit']) {
                $deliveryFees['deliveryFee1'] = $rate * ($shop['lower_limit'] - $totalPrice);
            }
            if ($pre_bill) {
                $tmpDelivery = $rate * ($shop['lower_limit'] - ($pre_bill['totalMaterielPrice'] + $totalPrice));
                $tmpDelivery = $tmpDelivery < 0 ? 0 : $tmpDelivery;
                $deliveryFees['deliveryFee1'] = $tmpDelivery - $pre_bill['deliveryFee1'];
            }

        } else if ($shop['limit_mode'] == 2) {
            //按属性计算运费
            $shopLimit = $this->getShopLimit($shop['ShopID']);
            if ($pre_bill) {
                //计算已存在第二单的运费
                foreach ($materielPrices as $key => $price) {
                    if (!in_array($key, [1001, 1002])) {
                        continue;
                    }

                    $pre_price = isset($pre_bill['prices'][$key]) ? $pre_bill['prices'][$key] : 0;
                    $tmpDelivery = $rate * ($shopLimit[$key] - ($pre_price + $price));
                    $tmpDelivery = $tmpDelivery < 0 ? 0 : $tmpDelivery;
                    if ($key == 1001) {
                        $deliveryFees['deliveryFee1'] = $tmpDelivery - $pre_bill['deliveryFee1'];
                    } else if ($key == 1002) {
                        $deliveryFees['deliveryFee2'] = $tmpDelivery - $pre_bill['deliveryFee2'];
                    }
                }

            } else {
                //计算当天第一单运费
                foreach ($materielPrices as $key => $price) {
                    $lower_limit = isset($shopLimit[$key]) ? $shopLimit[$key] : 0;
                    $tmpDelivery = $rate * ($lower_limit - $price);
                    if ($key == 1001) {
                        $deliveryFees['deliveryFee1'] = $tmpDelivery < 0 ? 0 : $tmpDelivery;
                    } else if ($key == 1002) {
                        $deliveryFees['deliveryFee2'] = $tmpDelivery < 0 ? 0 : $tmpDelivery;
                    }
                }
            }
        }
        return $deliveryFees;
    }

    public function actionGetDeliveryFee()
    {
        $data = Yii::$app->request->post();

        if (!isset($data['list']) || !is_array($data['list'])) {
            $data['list'] = [];
        }
        if (!isset($data['shopId']) || empty($data['shopId'])
        ) {
            $this->retJson('参数错误', 500, ['参数错误,请刷新重试']);
        }

        //检查门店
        $ckSql = "SELECT ShopID,ShopName,Address,lower_limit,limit_mode FROM j_shop WHERE ShopID ='" . $data['shopId'] . "'";
        $ckShop = Yii::$app->db->createCommand($ckSql)->queryOne();
        if (!$ckShop) $this->retJson('门店信息有误', 500, ['门店信息有误']);

        //商品
        $model = new Materiel();
        $materielArray = array();

        foreach ($data['list'] as $ma) {
            if (!isset($ma['materielId']) || empty($ma['materielId']) || !isset($ma['amount']) || empty($ma['amount'])) {
                continue;
            }
            if ($ma['amount'] <= 0) {
                continue;
            }
            $materielId = $ma['materielId'];
            $ckMa = $model::find()->where(['id' => $materielId, 'saleFlg' => 1, 'useFlg' => 1])->asArray()->one();
            if (!$ckMa) {
                continue;
            }
            $ckMa['qty'] = $ma['amount'];
            $materielArray[] = $ckMa;
        }

        $deliveryFees = $this->calcDeliveryFee($ckShop, $materielArray);
        $this->retJson('成功', 200, $deliveryFees);
    }


    public function actionCheckShopLimit()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['list']) || !is_array($data['list'])
            || !isset($data['shopId']) || empty($data['shopId'])
        ) {
            $this->retJson('参数错误', 500, ['参数错误,请刷新重试']);
        }

        //检查门店
        $ckSql = "SELECT ShopID,ShopName,Address,lower_limit,limit_mode FROM j_shop WHERE ShopID ='" . $data['shopId'] . "'";
        $ckShop = Yii::$app->db->createCommand($ckSql)->queryOne();
        if (!$ckShop) $this->retJson('门店信息有误', 500, ['门店信息有误']);


        //商品
        $model = new Materiel();
        $materielArray = array();


        $warn = [];
        foreach ($data['list'] as $ma) {
            if (!isset($ma['materielId']) || empty($ma['materielId']) || !isset($ma['amount']) || empty($ma['amount'])) {
                $warn[] = "[" . $ma['materielName'] . "]数据异常,请返回购物车重试";
            }

            if ($ma['amount'] <= 0) {
                $warn[] = "[" . $ma['materielName'] . "]订货数量异常,请返回购物车重试";
            }

            $materielId = $ma['materielId'];
            $ckMa = $model::find()->where(['id' => $materielId, 'saleFlg' => 1, 'useFlg' => 1])->asArray()->one();

            if (!$ckMa) {
                $warn[] = "[" . $ma['materielName'] . "]商品不存在或已下架,请返回购物车重试";
            }


            $curDate = date('Y-m-d');
            if ($ckMa['startTime'] > $curDate || $ckMa['endTime'] < $curDate) {
                $warn[] = '【' . $ckMa['materielName'] . '】 当前时间不可订购';
            }


            //检查门店是否可以采购该商品
            if ($ckMa['shopGroupId']) {

                $sql = "SELECT GROUP_CONCAT(j_shop_group.shopIds) AS shopIds from j_shop_group where FIND_IN_SET(j_shop_group.id,'" . $ckMa['shopGroupId'] . "')";
                $shopIdArr = Yii::$app->db->createCommand($sql)->queryOne();
                if (!in_array($data['shopId'], explode(',', $shopIdArr['shopIds']))) {
                    $warn[] = '当前门店不可购买【' . $ckMa['materielName'] . '】';
                }
            }

            $ckMa['qty'] = $ma['amount'];
            $materielArray[] = $ckMa;
        }
//        if ($warn) {
//            $this->retJson('错误', 500, $warn);
//        }
//
//
//        $payPrice = 0;
//        $materielPricesByStore = [];
//        foreach ($materielArray as $ma) {
//            $payPrice += ($ma['qty'] * $ma['salePrice']);
//            $subPrice = $ma['qty'] * $ma['salePrice'];
//            if (isset($materielPricesByStore[$ma['storeType']])) {
//                $materielPricesByStore[$ma['storeType']] += $subPrice;
//            } else {
//                $materielPricesByStore[$ma['storeType']] = $subPrice;
//            }
//        }
//
//
//        if ($ckShop['limit_mode'] == 1) {
//            if ($payPrice < $ckShop['lower_limit']) {
//                $warn[] = '订单金额小于' . $ckShop['lower_limit'] . '元,无法订货';
//            }
//        } else if ($ckShop['limit_mode'] == 2) {
//            $ck_limit_sql = "SELECT sc.config_key,sc.config_value,sl.lower_limit from j_sys_config sc
//                                left join j_shop_limit sl on sc.config_key = sl.storeType and sl.shopId = " . $data['shopId'] . "
//                                where sc.config_group_id = 'storeType'";
//            $shopStoreLimit = Yii::$app->db->createCommand($ck_limit_sql)->queryAll();
//
//            $tmpStoreLimit = [];
//
//            foreach ($shopStoreLimit as $limit) {
//                $tmpStoreLimit[$limit['config_key']] = $limit;
//            }
//
//            foreach ($materielPricesByStore as $key => $price) {
//                if (!isset($tmpStoreLimit[$key]) || !$tmpStoreLimit[$key]['lower_limit'] || $tmpStoreLimit[$key]['lower_limit'] == null || $price < $tmpStoreLimit[$key]['lower_limit']) {
//                    $warn[] = '【' . $tmpStoreLimit[$key]['config_value'] . '】类型物料订货金额不足 ' . $tmpStoreLimit[$key]['lower_limit'] . "元,无法订货";
//                }
//            }
//        }

        if ($warn) {
            $this->retJson('错误', 500, $warn);
        } else {
            $this->retJson('成功', 200);
        }
    }


    //新增预定单
    public function actionAddPreBill()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId'])
            || !isset($data['list']) || !is_array($data['list'])
            || !isset($data['shopId']) || empty($data['shopId'])
            || !isset($data['platform']) || empty($data['platform'])
        ) {
            $this->retJson('参数错误', 500);
        }


        //检查门店
        $ckSql = "SELECT ShopID,ShopName,Address,lower_limit,limit_mode FROM j_shop WHERE ShopID ='" . $data['shopId'] . "'";
        $ckShop = Yii::$app->db->createCommand($ckSql)->queryOne();
        if (!$ckShop) $this->retJson('门店信息有误', 500);

        if ($ckShop['limit_mode'] != 0) {

            //每天最多两单限制
            $curDate = date('Y-m-d'); //当前日期
            $sql = "SELECT preBillNo,billStatus FROM j_bill_pre WHERE ShopID = " . $data['shopId'] . " AND billStatus IN (1,2) AND createTime >= '" . $curDate . " 00:00:00' AND createTime <= '" . $curDate . " 23:59:59'";
            $bill_count = Yii::$app->db->createCommand($sql)->queryAll();
            foreach ($bill_count as $bc) {
                if ($bc['billStatus'] == 1) {
                    $this->retJson('请先处理前一笔未支付的订单', 500);
                    return;
                }
            }
            if (count($bill_count) >= 2) {
                $this->retJson('每天最多提交两笔有效订单', 500);
            }

        }


        $address = $ckShop['Address'];

        //商品
        $model = new Materiel();
        $materielArray = array();

        foreach ($data['list'] as $ma) {
            if (!isset($ma['materielId']) || empty($ma['materielId']) || !isset($ma['amount']) || empty($ma['amount']))
                $this->retJson('商品数据异常', 500);

            if ($ma['amount'] <= 0)
                $this->retJson('数量不正常', 500);


            $materielId = $ma['materielId'];
            $ckMa = $model::find()->where(['id' => $materielId, 'saleFlg' => 1, 'useFlg' => 1])->asArray()->one();

            if (!$ckMa) $this->retJson('商品状态异常,请返回购物车重试', 501, array('materielId' => $materielId));

            $curDate = date('Y-m-d');
            if ($ckMa['startTime'] > $curDate || $ckMa['endTime'] < $curDate) {
                $this->retJson('【' . $ckMa['materielName'] . '】 当前时间不可订购', 503, array('materielId' => $materielId));
            }


            //检查门店是否可以采购该商品
            if ($ckMa['shopGroupId']) {

                $sql = "SELECT GROUP_CONCAT(j_shop_group.shopIds) AS shopIds from j_shop_group where FIND_IN_SET(j_shop_group.id,'" . $ckMa['shopGroupId'] . "')";
                $shopIdArr = Yii::$app->db->createCommand($sql)->queryOne();
                if (!in_array($data['shopId'], explode(',', $shopIdArr['shopIds']))) {
                    $this->retJson('当前门店不可购买【' . $ckMa['materielName'] . '】', 502, array('materielId' => $materielId));
                }
            }


            $ckMa['qty'] = $ma['amount'];
            $materielArray[] = $ckMa;
        }

        $billDtl = [];
        $preBillNo = tools::getBillNo(date('Ymd'), 'seq_bill_pay_no', 6);
        $newTime = date('Y-m-d H:i:s');


//        $payPrice = 0;
        $totalQty = 0;
        $totalAmount = 0;
        $totalMaterielPrice = 0;

//        $materielPricesByStore = [];

        foreach ($materielArray as $ma) {
            $billDtl[] = array(
                'creator' => $data['userId'],
                'createTime' => $newTime,
                'preBillNo' => $preBillNo,
                'materielId' => $ma['id'],
                'qty' => $ma['qty'],
                'salePrice' => $ma['salePrice'],
                'referPrice' => $ma['referPrice'],
                'warehouseId' => $ma['warehouseId']
            );

            //$payPrice += ($ma['qty'] * $ma['salePrice']);
            $totalQty += $ma['qty'];
            $totalAmount += ($ma['qty'] * $ma['referPrice']);
            $totalMaterielPrice += ($ma['qty'] * $ma['salePrice']);

//            $subPrice = $ma['qty'] * $ma['salePrice'];
//            if (isset($materielPricesByStore[$ma['storeType']])) {
//                $materielPricesByStore[$ma['storeType']] += $subPrice;
//            } else {
//                $materielPricesByStore[$ma['storeType']] = $subPrice;
//            }
        }

        $deliveryFee = $this->calcDeliveryFee($ckShop, $materielArray);

        $billArr = array(
            'preBillNo' => $preBillNo,
            'creator' => $data['userId'],
            'createTime' => $newTime,
            'orderType' => 1, //1前台 2后台
            'billStatus' => 1,
            'userId' => $data['userId'],
            'shopId' => $data['shopId'],
            'address' => $address,
            'payPrice' => $totalMaterielPrice + $deliveryFee['deliveryFee1'] + $deliveryFee['deliveryFee2'],
            'totalQty' => $totalQty,
            'totalAmount' => $totalAmount,
            'platform' => $data['platform'],
            'totalMaterielPrice' => $totalMaterielPrice,
            'deliveryFee1' => $deliveryFee['deliveryFee1'],
            'deliveryFee2' => $deliveryFee['deliveryFee2'],
        );

//
//        if ($ckShop['limit_mode'] == 1) {
//            if ($payPrice < $ckShop['lower_limit']) {
//                $this->retJson('订单金额小于' . $ckShop['lower_limit'] . '元,提交失败', 500);
//            }
//        } else if ($ckShop['limit_mode'] == 2) {
//            $ck_limit_sql = "SELECT sc.config_key,sc.config_value,sl.lower_limit from j_sys_config sc
//                                left join j_shop_limit sl on sc.config_key = sl.storeType and sl.shopId = " . $data['shopId'] . "
//                                where sc.config_group_id = 'storeType'";
//            $shopStoreLimit = Yii::$app->db->createCommand($ck_limit_sql)->queryAll();
//
//            $tmpStoreLimit = [];
//
//            foreach ($shopStoreLimit as $limit) {
//                $tmpStoreLimit[$limit['config_key']] = $limit;
//            }
//
//
//            foreach ($materielPricesByStore as $key => $price) {
//                if (!isset($tmpStoreLimit[$key]) || !$tmpStoreLimit[$key]['lower_limit'] || $tmpStoreLimit[$key]['lower_limit'] == null || $price < $tmpStoreLimit[$key]['lower_limit']) {
//                    $this->retJson('【' . $tmpStoreLimit[$key]['config_value'] . '】类型物料订货金额不足 ' . $tmpStoreLimit[$key]['lower_limit'] . "元,提交失败", 500, array('materielId' => $materielId));
//                }
//            }
//        }


        $transaction = Yii::$app->db->beginTransaction();
        try {
            //添加订单

            Yii::$app->db->createCommand()->insert('j_bill_pre', $billArr)->execute();
            //添加订单明细
            //$delSql = '';
            foreach ($billDtl as $addDtl) {
                Yii::$app->db->createCommand()->insert('j_bill_dtl_pre', $addDtl)->execute();
            }

            $transaction->commit();
            $this->retJson('操作成功', 200, $billArr);
        } catch (\Exception $e) {
            $transaction->rollBack();
            Yii::error("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('数据异常,请重试', 500);
        }
    }

    public function actionCancelPreBill()
    {
        $data = Yii::$app->request->post();
        $payBillNo = $data['preBillNo'];
        $sql = "UPDATE j_bill_pre SET billStatus = 0 WHERE preBillNo = '{$payBillNo}' AND billStatus = 1";
        $result = Yii::$app->db->createCommand($sql)->execute();
        if ($result) {
            $this->retJson('操作成功', 200);
        } else {
            $this->retJson('取消失败,当前订单不可取消', 500);
        }
    }


    //支付成功
    public function actionPayedBill()
    {
        $data = Yii::$app->request->post();
        $payBillNo = $data['preBillNo'];
        $payTime = $data['payTime'];

        $sql = "UPDATE j_bill_pre SET billStatus = 2,payTime='{$payTime}' WHERE preBillNo = '{$payBillNo}' AND billStatus != 2";
        $result = Yii::$app->db->createCommand($sql)->execute();
        if ($result) {
            $preBillSql = "SELECT * FROM j_bill_pre WHERE preBillNo = '{$payBillNo}'";
            $preBill = Yii::$app->db->createCommand($preBillSql)->queryOne();

            $preBillDtlSql = "SELECT * FROM j_bill_dtl_pre WHERE preBillNo = '{$payBillNo}'";
            $preBillDtlList = Yii::$app->db->createCommand($preBillDtlSql)->queryAll();

            $newTime = date('Y-m-d H:i:s');
            $tempGroup = [];
            foreach ($preBillDtlList as $dtl) {
                $tempGroup[$dtl['warehouseId']][] = $dtl;
            }

            $billArr = [];
            $billDtl = [];
            $billNos = [];
            foreach ($tempGroup as $warehouseId => $dtls) {


                $billNo = tools::getBillNo(date('Ymd'), 'seq_bill_no', 6);
                $ck_bil_no = Yii::$app->db->createCommand("SELECT count(0) cnt FROM j_bill WHERE billNo='" . $billNo . "'")->queryOne();
                if ($ck_bil_no['cnt']) {
                    $this->retJson('网络异常，请重试', 500);
                }

                $subQty = 0;
                $subPrice = 0;
                foreach ($dtls as $dtl) { //订单明细
                    $billDtl[] = array(
                        'creator' => $preBill['userId'],
                        'createTime' => $newTime,
                        'billNo' => $billNo,
                        'materielId' => $dtl['materielId'],
                        'qty' => $dtl['qty'],
                        'deliverQty' => 0,
                        'deliverAmount' => 0,
                    );
                    $subQty += $dtl['qty'];
                    $subPrice += ($dtl['qty'] * $dtl['referPrice']);
                }

                $billArr[] = array(
                    'billNo' => $billNo,
                    'creator' => $preBill['userId'],
                    'createTime' => $newTime,
                    'orderType' => 1, //1前台 2后台
                    'billStatus' => 0,
                    'userId' => $preBill['userId'],
                    'warehouseId' => $warehouseId,
                    'sendDate' => date("Y-m-d", strtotime("+1 day")),
                    'shopId' => $preBill['shopId'],
                    'address' => $preBill['address'],
                    'totalQty' => $subQty,
                    'totalAmount' => $subPrice,
                );

                $billNos[] = $billNo;

            }
            $transaction = Yii::$app->db->beginTransaction();
            try {

                $billNoValue = implode(",", $billNos);
                $billNosql = "UPDATE j_bill_pre SET billNo = '{$billNoValue}' WHERE preBillNo = '{$payBillNo}'";
                $result = Yii::$app->db->createCommand($billNosql)->execute();

                //添加订单
                foreach ($billArr as $bill) {
                    Yii::$app->db->createCommand()->insert('j_bill', $bill)->execute();
                }
                //添加订单明细
                $delSql = '';
                foreach ($billDtl as $addDtl) {
                    Yii::$app->db->createCommand()->insert('j_bill_dtl', $addDtl)->execute();
                    $delSql .= "DELETE FROM j_cart WHERE materielId='{$addDtl['materielId']}' AND userId='{$preBill['userId']}';";
                }
                Yii::$app->db->createCommand($delSql)->execute();

                $transaction->commit();
                $this->retJson('操作成功', 200);
            } catch (\Exception $e) {
                $transaction->rollBack();
                Yii::error("异常:" . $e->getMessage() . $e->getLine());
                $this->retJson('数据异常,请重试', 500);
            }
        }

        $this->retJson('数据异常,请重试', 500);

    }

    /**
     * 查询支付订单详情
     */
    public function actionPreBill()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['preBillNo']) || empty($data['preBillNo'])) {
            $this->retJson('参数错误', 500);
        }


        $sql = "SELECT b.preBillNo,b.createTime,b.totalQty,b.totalAmount,b.payPrice,b.totalMaterielPrice,b.deliveryFee1,b.deliveryFee2,b.billStatus,sh.ShopName,b.address,b.billNo,b.platform FROM j_bill_pre b
                INNER JOIN j_shop sh ON b.shopId=sh.ShopID
                WHERE b.preBillNo = '{$data['preBillNo']}'";

        $billInfo = Yii::$app->db->createCommand($sql)->queryOne();
        if (!$billInfo) {
            $this->retJson('未找到订单', 500);
        }
        $statusArr = ['0' => '已取消', '1' => '未支付', '2' => '已支付'];
        $billInfo['statusName'] = $statusArr[$billInfo['billStatus']];


        $dtlSql = "SELECT ma.materielCode,ma.materielName,ma.packDesc,ma.specDesc,ma.orderUnit,bd.qty,bd.salePrice,bd.materielId
              FROM j_bill_dtl_pre bd inner join j_materiel ma on 
              bd.materielId=ma.id where bd.prebillNo ='{$data['preBillNo']}'";


        $dtlArr = Yii::$app->db->createCommand($dtlSql)->queryAll();
        $billInfo['dtl'] = $dtlArr;

        $this->retJson('操作成功', 200, $billInfo);
    }


    public function actionCancelOvertimePreBill()
    {
        $date = date("Y-m-d H:i:s", strtotime("-15 minute"));
        $sql = "UPDATE j_bill_pre set billStatus = 0  WHERE createTime <  '{$date}' AND billStatus = 1";
        Yii::$app->db->createCommand($sql)->execute();
    }


    //新增订单
    public function actionAddBill()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId'])
            || !isset($data['list']) || !is_array($data['list'])
            || !isset($data['shopId']) || empty($data['shopId'])
        ) {
            $this->retJson('参数错误', 500);
        }

        //检查门店
        $ckSql = "SELECT ShopName,Address,shopType FROM j_shop WHERE ShopID ='" . $data['shopId'] . "'";
        $ckShop = Yii::$app->db->createCommand($ckSql)->queryOne();
        if (!$ckShop) $this->retJson('门店信息有误', 500);
        if ($ckShop['shopType'] != 0) $this->retJson('门店信息有误!', 500);


        $address = $ckShop['Address'];

        //商品
        $model = new Materiel();
        $groupArr = array();

        foreach ($data['list'] as $ma) {
            if (!isset($ma['materielId']) || empty($ma['materielId']) || !isset($ma['amount']) || empty($ma['amount']))
                $this->retJson('商品数据异常', 500);

            if ($ma['amount'] <= 0)
                $this->retJson('数量不正常', 500);

            $materielId = $ma['materielId'];
            $ckMa = $model::find()->where(['id' => $materielId, 'saleFlg' => 1, 'useFlg' => 1])->asArray()->one();
            if (!$ckMa) $this->retJson('商品状态异常,请返回购物车重试', 501, array('materielId' => $materielId));

            $curDate = date('Y-m-d');
            if ($ckMa['startTime'] > $curDate || $ckMa['endTime'] < $curDate) {
                $this->retJson('【' . $ckMa['materielName'] . '】 当前时间不可订购', 503, array('materielId' => $materielId));
            }


            //检查门店是否可以采购该商品
            if ($ckMa['shopGroupId']) {
                $sql = "SELECT GROUP_CONCAT(j_shop_group.shopIds) AS shopIds from j_shop_group where FIND_IN_SET(j_shop_group.id,'" . $ckMa['shopGroupId'] . "')";
                $shopIdArr = Yii::$app->db->createCommand($sql)->queryOne();
                if (!in_array($data['shopId'], explode(',', $shopIdArr['shopIds']))) {
                    $this->retJson('当前门店不可购买【' . $ckMa['materielName'] . '】', 502, array('materielId' => $materielId));
                }
            }

            $ckMa['orderQty'] = $ma['amount'];
            $groupArr[$ckMa['warehouseId']][] = $ckMa;
        }

        $billArr = $billDtl = [];


        $newTime = date('Y-m-d H:i:s');
        foreach ($groupArr as $warehouseId => $gma) {
            $deliverQty = 0;
            $deliverAmount = 0;

            $billNo = tools::getBillNo(date('Ymd'), 'seq_bill_no', 6);
            $ck_bil_no = Yii::$app->db->createCommand("SELECT count(0) cnt FROM j_bill WHERE billNo='" . $billNo . "'")->queryOne();
            if ($ck_bil_no['cnt']) {
                $this->retJson('网络异常，请重试', 500);
            }

            foreach ($gma as $dtl) {
                //订单明细
                $billDtl[] = array(
                    'creator' => $data['userId'],
                    'createTime' => $newTime,
                    'billNo' => $billNo,
                    'materielId' => $dtl['id'],
                    'qty' => $dtl['orderQty'],
                    'deliverQty' => 0,
                    'deliverAmount' => 0,
                );
                $deliverQty += $dtl['orderQty'];
                $deliverAmount += $dtl['orderQty'] * $dtl['referPrice'];
            }
            $billArr[] = array(
                'billNo' => $billNo,
                'creator' => $data['userId'],
                'createTime' => $newTime,
                'orderType' => 1, //1前台 2后台
                'billStatus' => 0,
                'userId' => $data['userId'],
                'warehouseId' => $warehouseId,
                'sendDate' => date("Y-m-d", strtotime("+1 day")),
                'shopId' => $data['shopId'],
                'address' => $address,
                'totalQty' => $deliverQty,
                'totalAmount' => $deliverAmount,
            );
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            //添加订单

            foreach ($billArr as $bill) {
                Yii::$app->db->createCommand()->insert('j_bill', $bill)->execute();
            }
            //添加订单明细
            $delSql = '';
            foreach ($billDtl as $addDtl) {
                Yii::$app->db->createCommand()->insert('j_bill_dtl', $addDtl)->execute();
                $delSql .= "DELETE FROM j_cart WHERE materielId='" . $addDtl['materielId'] . "' AND userId='" . $data['userId'] . "';";
            }
            Yii::$app->db->createCommand($delSql)->execute();

            $transaction->commit();
            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            Yii::error("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('数据异常,请重试', 500);
        }
    }


    public function actionUploadImage()
    {
        $data = Yii::$app->request->post();
        $imgbase64 = $data['imgbase64'];
        $uuid = Uuid::uuid();
        $idx_1 = strpos($imgbase64, '/') + 1;
        $idx_2 = strpos($imgbase64, ';');
        $suffix = substr($imgbase64, $idx_1, $idx_2 - $idx_1);
        $binary = explode(',', $imgbase64);

        $temp = 'receipt/' . date('Ymd') . '/';
        $fileName = $uuid . $suffix;
        $this->commUpload($temp, $binary[1], $fileName);
        $this->retJson('操作成功', 200, $temp . $fileName);
    }


    //订单收货
    public function actionReceipt()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId']) ||
            !isset($data['billNo']) || empty($data['billNo']) ||
            !isset($data['list']) || !is_array($data['list'])) {
            $this->retJson('参数错误', 500);
        }

        $bill = Yii::$app->db->createCommand("SELECT * FROM j_bill WHERE billStatus=2 AND billNo='" . $data['billNo'] . "'")->queryOne();
        if (!$bill) $this->retJson('订单信息有误,请刷新重试', 500);

        $strSql = '';
        $diffArr = null;
        $imgData = isset($data['imgData']) ? $data['imgData'] : array();
        $now = date('Y-m-d');
        $nowDate = date('Ymd');
        $newTime = date('Y-m-d H:i:s');

        $model = new Materiel();
        foreach ($data['list'] as $ma) {
            if (!isset($ma['materielId']) || empty($ma['materielId']) || !isset($ma['amount'])) {
                $this->retJson('商品数据异常', 500);
            }

            $ckMa = $model::find()->where(['id' => $ma['materielId']])->asArray()->one();
            if (!$ckMa) {
                $this->retJson('商品数据异常', 500);
            }

            $ckSql = "SELECT qty,deliverQty FROM j_bill_dtl WHERE billNo ='" . $data['billNo'] . "' AND materielId='" . $ma['materielId'] . "'";
            $bill_dtl = Yii::$app->db->createCommand($ckSql)->queryOne();
            if (!$bill_dtl) $this->retJson('商品数据异常', 500);

            $remark = '';
            if (isset($ma['remark']) && !empty($ma['remark'])) $remark = $ma['remark'];
            $receiptAmount = round($ckMa['referPrice'] * $ma['amount'], 4);
            $strSql .= "UPDATE j_bill_dtl SET receiptQty=" . $ma['amount'] . ",receiptAmount=" . $receiptAmount . " ,remark='" . $remark . "' WHERE billNo ='" . $data['billNo'] . "' AND materielId='" . $ma['materielId'] . "';";

            //图片
            if (isset($imgData[$ma['materielId']])) {
                foreach ($imgData[$ma['materielId']] as $key => &$img) {
//                    $idx_1 = strpos($img, '/') + 1;
//                    $idx_2 = strpos($img, ';');
//                    $suffix = substr($img, $idx_1, $idx_2 - $idx_1);
//                    $binary = explode(',', $img);
//
//                    $temp = 'receipt/' . date('Ymd') . '/';
//                    $fileName = $data['billNo'] . $key . '.' . $suffix;
//                    $this->commUpload($temp, $binary[1], $fileName);
                    $strSql .= "INSERT INTO j_bill_ext(creator,createTime,billNo,materielId,filePath) VALUES
                    ('" . $data['userId'] . "',now(),'" . $data['billNo'] . "','" . $ma['materielId'] . "',
                     '" . $img . "');";
                }
            }

            if ($ckMa['storeFlg']) {
                //管库存 异常收获数据
                if ($bill_dtl['deliverQty'] != $ma['amount']) {
                    if (!isset($diffArr[$data['billNo']])) {
                        $diffArr[$data['billNo']] = array(
                            'billNo' => $data['billNo'],
                            'creator' => $data['userId'],
                            'createTime' => $newTime,
                            'diffStatus' => 0
                        );
                    }

                    $diffArr[$data['billNo']]['dtl'][] = array(
                        'creator' => $data['userId'],
                        'createTime' => $newTime,
                        'billNo' => $data['billNo'],
                        'materielId' => $ma['materielId'],
                        'qty' => $bill_dtl['qty'],
                        'deliverQty' => $bill_dtl['deliverQty'],
                        'receiptQty' => $ma['amount'],
                    );
                }
            } else {
                //无库存的商品 直接入门店库存
                $ckSql = "select max(batch) batch from j_shop_stock where materielId='" . $ma['materielId'] . "' and batch like '" . $nowDate . "%'";
                $max_bath = Yii::$app->db->createCommand($ckSql)->queryOne();
                if ($max_bath && $max_bath['batch']) {
                    $batch = $max_bath['batch'] + 1;
                } else {
                    $batch = $nowDate . '001';
                }
                $temp_supId = $ckMa['supplierId'];
                $temp_supId = explode(',', $temp_supId);
                $temp_supId = max($temp_supId);
                $strSql .= "INSERT INTO j_shop_stock (creator,createTime,materielId,shopId,warehouseId,supplierId,batch,
                      productDate,safeDate,price,total,qty,amount) VALUES
                      ('" . $data['userId'] . "','" . $newTime . "','" . $ma['materielId'] . "','" . $bill['shopId'] . "',
                       " . $ckMa['warehouseId'] . "," . $temp_supId . " ,'" . $batch . "',
                       '" . $now . "','" . $now . "'," . $ckMa['referPrice'] . "," . $ma['amount'] . ",
                       " . $ma['amount'] . "," . $ma['amount'] * $ckMa['referPrice'] . ");";
            }
        }

        $sql = "SELECT bb.deliverQty,ms.* FROM j_materiel_stock ms 
                INNER JOIN j_bill_batch bb ON ms.id=bb.stockId
                WHERE bb.billNo='" . $data['billNo'] . "'";
        $stockArr = Yii::$app->db->createCommand($sql)->queryAll();

        //转移库存
        foreach ($stockArr as $stock) {
            $ckSql = "SELECT COUNT(0) cnt FROM j_shop_stock WHERE materielId='" . $stock['materielId'] . "' 
                AND shopId='" . $bill['shopId'] . "' AND warehouseId=" . $stock['warehouseId'] . " 
                AND supplierId=" . $stock['supplierId'] . " AND batch='" . $stock['batch'] . "'";
            $res = Yii::$app->db->createCommand($ckSql)->queryOne();

            if ($res && $res['cnt']) {
                $strSql .= "UPDATE j_shop_stock SET qty=qty+" . $stock['deliverQty'] . ",amount=amount+(" . $stock['deliverQty'] . "*price) WHERE materielId='" . $stock['materielId'] . "' 
                    AND shopId='" . $bill['shopId'] . "' AND batch='" . $stock['batch'] . "';";
            } else {
                $strSql .= "INSERT INTO j_shop_stock (creator,createTime,materielId,shopId,warehouseId,supplierId,batch,
                      productDate,safeDate,price,total,qty,amount) VALUES
                      ('" . $data['userId'] . "','" . $newTime . "','" . $stock['materielId'] . "','" . $bill['shopId'] . "',
                       " . $stock['warehouseId'] . "," . $stock['supplierId'] . ",'" . $stock['batch'] . "',
                       '" . $stock['productDate'] . "','" . $stock['safeDate'] . "'," . $stock['price'] . "," . $stock['deliverQty'] . ",
                       " . $stock['deliverQty'] . "," . $stock['deliverQty'] * $stock['price'] . ");";
            }
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {

            Yii::$app->db->createCommand($strSql)->execute();
            Yii::$app->db->createCommand("UPDATE j_bill SET billStatus=3,sendee='" . $data['userId'] . "',finishTime='" . $newTime . "' WHERE billNo='" . $data['billNo'] . "'")->execute();
            //释放冻结
            $sql = "UPDATE j_materiel_stock ms INNER JOIN j_bill_batch bb ON ms.id=bb.stockId
                    SET ms.freeze=ms.freeze-bb.deliverQty,ms.total=ms.total-bb.deliverQty,
                    ms.amount=ms.amount-(ms.price*bb.deliverQty)
                    WHERE bb.billNo='" . $data['billNo'] . "';";
            Yii::$app->db->createCommand($sql)->execute();

            //部分收货
            if ($diffArr) {
                foreach ($diffArr as $diff) {
                    foreach ($diff['dtl'] as $dtl) {
                        Yii::$app->db->createCommand()->insert('j_diff_dtl', $dtl)->execute();
                    }
                    unset($diff['dtl']);
                    Yii::$app->db->createCommand()->insert('j_diff', $diff)->execute();
                }
            }

            $transaction->commit();

            $this->retJson('操作成功', 200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            error_log("异常:" . $e->getMessage() . $e->getLine());
            $this->retJson('操作失败', 500);
        }
    }

    //订单列表
    public function actionList()
    {
        $data = Yii::$app->request->post();
        /*if (!isset($data['userId']) || empty($data['userId'])) {
                 $this->retJson('参数错误', 500);
             }*/

        $sql = "SELECT b.billNo,b.creator,b.createTime,b.totalQty,b.billStatus,wa.warehouseName,sh.ShopName FROM j_bill b
                INNER JOIN j_warehouse wa ON b.warehouseId=wa.id
                INNER JOIN j_shop sh ON b.shopId=sh.ShopID
                WHERE 1=1";

        if (isset($data['shopId']) && !empty($data['shopId'])) {
            $sql .= ' AND b.shopId IN(' . $data['shopId'] . ')';
        }

        if (isset($data['status']) && !empty($data['status'])) {
            if ($data['status'] == 1) $sql .= ' AND b.billStatus IN (0,1)';
            else $sql .= ' AND b.billStatus = ' . $data['status'];
        } else {
            $sql .= ' AND b.billStatus IN (0,1,2)';
        }
        $sql .= ' ORDER BY b.billNo DESC';


        $billArr = Yii::$app->db->createCommand($sql)->queryAll();

        $statusArr = ['0' => '待发货', '1' => '待发货', '2' => '已发货', '3' => '已收货', '9' => '作废'];
        if ($billArr) {
            foreach ($billArr as &$bill) {
                $bill['statusName'] = $statusArr[$bill['billStatus']];
            }
        }
        $this->retJson('操作成功', 200, $billArr);
    }


    //订单列表
    public function actionPreList()
    {
        $data = Yii::$app->request->post();
        /*if (!isset($data['userId']) || empty($data['userId'])) {
                 $this->retJson('参数错误', 500);
             }*/

        $sql = "SELECT b.preBillNo,b.creator,b.createTime,b.payPrice,b.billStatus,sh.ShopName FROM j_bill_pre b
                INNER JOIN j_shop sh ON b.shopId=sh.ShopID
                WHERE billStatus != 0";

        if (isset($data['shopId']) && !empty($data['shopId'])) {
            $sql .= ' AND b.shopId IN(' . $data['shopId'] . ')';
        }

        if (isset($data['status'])) {
            $sql .= ' AND b.billStatus = ' . $data['status'];
        }
        $sql .= ' ORDER BY b.preBillNo DESC';

        $billArr = Yii::$app->db->createCommand($sql)->queryAll();

        $statusArr = ['0' => '已取消', '1' => '待支付', '2' => '已支付'];
        if ($billArr) {
            foreach ($billArr as &$bill) {
                $bill['statusName'] = $statusArr[$bill['billStatus']];
            }
        }
        $this->retJson('操作成功', 200, $billArr);
    }


    //订单详情
    public function actionDetail()
    {
        $data = Yii::$app->request->post();
        if (!isset($data['userId']) || empty($data['userId']) && !isset($data['billNo']) || empty($data['billNo'])) {
            $this->retJson('参数错误', 500);
        }

        $sql = "SELECT b.billNo,b.createTime,b.totalQty,b.billStatus,wa.warehouseName,sh.ShopName,b.address FROM j_bill b
                INNER JOIN j_warehouse wa ON b.warehouseId=wa.id
                INNER JOIN j_shop sh ON b.shopId=sh.ShopID
                WHERE b.billNo = '" . $data['billNo'] . "'";

        $billInfo = Yii::$app->db->createCommand($sql)->queryOne();
        if (!$billInfo) {
            $this->retJson('未找到订单', 500);
        }
        $statusArr = ['0' => '待发货', '1' => '待发货', '2' => '已发货', '3' => '已收货', '9' => '作废'];
        $billInfo['statusName'] = $statusArr[$billInfo['billStatus']];

        $dtlSql = "SELECT ma.materielCode,ma.materielName,ma.packDesc,ma.specDesc,ma.orderUnit,bd.deliverQty,bd.qty,bd.materielId,
              bd.receiptQty,bd.remark FROM j_bill_dtl bd inner join j_materiel ma on 
              bd.materielId=ma.id where billNo ='" . $data['billNo'] . "'";
        $dtlArr = Yii::$app->db->createCommand($dtlSql)->queryAll();
        $billInfo['dtl'] = $dtlArr;

        $this->retJson('操作成功', 200, $billInfo);
    }

    //文件上传 图片、音效
    private function commUpload($path, $data, $fileName)
    {
        $data = base64_decode($data);
        $path = Yii::$app->params['IMG_UPLOAD_PATH'] . $path;
        if (!file_exists($path)) mkdir($path, 0777, true); //创建目录
        $filePath = $path . $fileName;

        try {
            $file = fopen($filePath, "w");               //打开文件准备写入
            fwrite($file, $data);                        //写入
            fclose($file);                              //关闭
            return true;
        } catch (Exception $e) {
            error_log("生成图片失败:" . $e->getMessage());
            return false;
        }
    }
}